home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / Miro_Downloader.exe / optparse.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-11-12  |  49.6 KB  |  1,524 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. """optparse - a powerful, extensible, and easy-to-use option parser.
  5.  
  6. By Greg Ward <gward@python.net>
  7.  
  8. Originally distributed as Optik; see http://optik.sourceforge.net/ .
  9.  
  10. If you have problems with this module, please do not file bugs,
  11. patches, or feature requests with Python; instead, use Optik's
  12. SourceForge project page:
  13.   http://sourceforge.net/projects/optik
  14.  
  15. For support, use the optik-users@lists.sourceforge.net mailing list
  16. (http://lists.sourceforge.net/lists/listinfo/optik-users).
  17. """
  18. __version__ = '1.5.3'
  19. __all__ = [
  20.     'Option',
  21.     'SUPPRESS_HELP',
  22.     'SUPPRESS_USAGE',
  23.     'Values',
  24.     'OptionContainer',
  25.     'OptionGroup',
  26.     'OptionParser',
  27.     'HelpFormatter',
  28.     'IndentedHelpFormatter',
  29.     'TitledHelpFormatter',
  30.     'OptParseError',
  31.     'OptionError',
  32.     'OptionConflictError',
  33.     'OptionValueError',
  34.     'BadOptionError']
  35. __copyright__ = '\nCopyright (c) 2001-2006 Gregory P. Ward.  All rights reserved.\nCopyright (c) 2002-2006 Python Software Foundation.  All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n  * Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n\n  * Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n\n  * Neither the name of the author nor the names of its\n    contributors may be used to endorse or promote products derived from\n    this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS\nIS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\nTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n'
  36. import sys
  37. import os
  38. import types
  39. import textwrap
  40.  
  41. def _repr(self):
  42.     return '<%s at 0x%x: %s>' % (self.__class__.__name__, id(self), self)
  43.  
  44.  
  45. try:
  46.     from gettext import gettext
  47. except ImportError:
  48.     
  49.     def gettext(message):
  50.         return message
  51.  
  52.  
  53. _ = gettext
  54.  
  55. class OptParseError(Exception):
  56.     
  57.     def __init__(self, msg):
  58.         self.msg = msg
  59.  
  60.     
  61.     def __str__(self):
  62.         return self.msg
  63.  
  64.  
  65.  
  66. class OptionError(OptParseError):
  67.     '''
  68.     Raised if an Option instance is created with invalid or
  69.     inconsistent arguments.
  70.     '''
  71.     
  72.     def __init__(self, msg, option):
  73.         self.msg = msg
  74.         self.option_id = str(option)
  75.  
  76.     
  77.     def __str__(self):
  78.         if self.option_id:
  79.             return 'option %s: %s' % (self.option_id, self.msg)
  80.         else:
  81.             return self.msg
  82.  
  83.  
  84.  
  85. class OptionConflictError(OptionError):
  86.     '''
  87.     Raised if conflicting options are added to an OptionParser.
  88.     '''
  89.     pass
  90.  
  91.  
  92. class OptionValueError(OptParseError):
  93.     '''
  94.     Raised if an invalid option value is encountered on the command
  95.     line.
  96.     '''
  97.     pass
  98.  
  99.  
  100. class BadOptionError(OptParseError):
  101.     '''
  102.     Raised if an invalid option is seen on the command line.
  103.     '''
  104.     
  105.     def __init__(self, opt_str):
  106.         self.opt_str = opt_str
  107.  
  108.     
  109.     def __str__(self):
  110.         return _('no such option: %s') % self.opt_str
  111.  
  112.  
  113.  
  114. class AmbiguousOptionError(BadOptionError):
  115.     '''
  116.     Raised if an ambiguous option is seen on the command line.
  117.     '''
  118.     
  119.     def __init__(self, opt_str, possibilities):
  120.         BadOptionError.__init__(self, opt_str)
  121.         self.possibilities = possibilities
  122.  
  123.     
  124.     def __str__(self):
  125.         return _('ambiguous option: %s (%s?)') % (self.opt_str, ', '.join(self.possibilities))
  126.  
  127.  
  128.  
  129. class HelpFormatter:
  130.     '''
  131.     Abstract base class for formatting option help.  OptionParser
  132.     instances should use one of the HelpFormatter subclasses for
  133.     formatting help; by default IndentedHelpFormatter is used.
  134.  
  135.     Instance attributes:
  136.       parser : OptionParser
  137.         the controlling OptionParser instance
  138.       indent_increment : int
  139.         the number of columns to indent per nesting level
  140.       max_help_position : int
  141.         the maximum starting column for option help text
  142.       help_position : int
  143.         the calculated starting column for option help text;
  144.         initially the same as the maximum
  145.       width : int
  146.         total number of columns for output (pass None to constructor for
  147.         this value to be taken from the $COLUMNS environment variable)
  148.       level : int
  149.         current indentation level
  150.       current_indent : int
  151.         current indentation level (in columns)
  152.       help_width : int
  153.         number of columns available for option help text (calculated)
  154.       default_tag : str
  155.         text to replace with each option\'s default value, "%default"
  156.         by default.  Set to false value to disable default value expansion.
  157.       option_strings : { Option : str }
  158.         maps Option instances to the snippet of help text explaining
  159.         the syntax of that option, e.g. "-h, --help" or
  160.         "-fFILE, --file=FILE"
  161.       _short_opt_fmt : str
  162.         format string controlling how short options with values are
  163.         printed in help text.  Must be either "%s%s" ("-fFILE") or
  164.         "%s %s" ("-f FILE"), because those are the two syntaxes that
  165.         Optik supports.
  166.       _long_opt_fmt : str
  167.         similar but for long options; must be either "%s %s" ("--file FILE")
  168.         or "%s=%s" ("--file=FILE").
  169.     '''
  170.     NO_DEFAULT_VALUE = 'none'
  171.     
  172.     def __init__(self, indent_increment, max_help_position, width, short_first):
  173.         self.parser = None
  174.         self.indent_increment = indent_increment
  175.         self.help_position = self.max_help_position = max_help_position
  176.         if width is None:
  177.             
  178.             try:
  179.                 width = int(os.environ['COLUMNS'])
  180.             except (KeyError, ValueError):
  181.                 width = 80
  182.  
  183.             width -= 2
  184.         
  185.         self.width = width
  186.         self.current_indent = 0
  187.         self.level = 0
  188.         self.help_width = None
  189.         self.short_first = short_first
  190.         self.default_tag = '%default'
  191.         self.option_strings = { }
  192.         self._short_opt_fmt = '%s %s'
  193.         self._long_opt_fmt = '%s=%s'
  194.  
  195.     
  196.     def set_parser(self, parser):
  197.         self.parser = parser
  198.  
  199.     
  200.     def set_short_opt_delimiter(self, delim):
  201.         if delim not in ('', ' '):
  202.             raise ValueError('invalid metavar delimiter for short options: %r' % delim)
  203.         
  204.         self._short_opt_fmt = '%s' + delim + '%s'
  205.  
  206.     
  207.     def set_long_opt_delimiter(self, delim):
  208.         if delim not in ('=', ' '):
  209.             raise ValueError('invalid metavar delimiter for long options: %r' % delim)
  210.         
  211.         self._long_opt_fmt = '%s' + delim + '%s'
  212.  
  213.     
  214.     def indent(self):
  215.         self.current_indent += self.indent_increment
  216.         self.level += 1
  217.  
  218.     
  219.     def dedent(self):
  220.         self.current_indent -= self.indent_increment
  221.         if not self.current_indent >= 0:
  222.             raise AssertionError, 'Indent decreased below 0.'
  223.         self
  224.         self.level -= 1
  225.  
  226.     
  227.     def format_usage(self, usage):
  228.         raise NotImplementedError, 'subclasses must implement'
  229.  
  230.     
  231.     def format_heading(self, heading):
  232.         raise NotImplementedError, 'subclasses must implement'
  233.  
  234.     
  235.     def _format_text(self, text):
  236.         '''
  237.         Format a paragraph of free-form text for inclusion in the
  238.         help output at the current indentation level.
  239.         '''
  240.         text_width = self.width - self.current_indent
  241.         indent = ' ' * self.current_indent
  242.         return textwrap.fill(text, text_width, initial_indent = indent, subsequent_indent = indent)
  243.  
  244.     
  245.     def format_description(self, description):
  246.         if description:
  247.             return self._format_text(description) + '\n'
  248.         else:
  249.             return ''
  250.  
  251.     
  252.     def format_epilog(self, epilog):
  253.         if epilog:
  254.             return '\n' + self._format_text(epilog) + '\n'
  255.         else:
  256.             return ''
  257.  
  258.     
  259.     def expand_default(self, option):
  260.         if self.parser is None or not (self.default_tag):
  261.             return option.help
  262.         
  263.         default_value = self.parser.defaults.get(option.dest)
  264.         if default_value is NO_DEFAULT or default_value is None:
  265.             default_value = self.NO_DEFAULT_VALUE
  266.         
  267.         return option.help.replace(self.default_tag, str(default_value))
  268.  
  269.     
  270.     def format_option(self, option):
  271.         result = []
  272.         opts = self.option_strings[option]
  273.         opt_width = self.help_position - self.current_indent - 2
  274.         if len(opts) > opt_width:
  275.             opts = '%*s%s\n' % (self.current_indent, '', opts)
  276.             indent_first = self.help_position
  277.         else:
  278.             opts = '%*s%-*s  ' % (self.current_indent, '', opt_width, opts)
  279.             indent_first = 0
  280.         result.append(opts)
  281.         if option.help:
  282.             help_text = self.expand_default(option)
  283.             help_lines = textwrap.wrap(help_text, self.help_width)
  284.             result.append('%*s%s\n' % (indent_first, '', help_lines[0]))
  285.             []([ '%*s%s\n' % (self.help_position, '', line) for line in help_lines[1:] ])
  286.         elif opts[-1] != '\n':
  287.             result.append('\n')
  288.         
  289.         return ''.join(result)
  290.  
  291.     
  292.     def store_option_strings(self, parser):
  293.         self.indent()
  294.         max_len = 0
  295.         for opt in parser.option_list:
  296.             strings = self.format_option_strings(opt)
  297.             self.option_strings[opt] = strings
  298.             max_len = max(max_len, len(strings) + self.current_indent)
  299.         
  300.         self.indent()
  301.         for group in parser.option_groups:
  302.             for opt in group.option_list:
  303.                 strings = self.format_option_strings(opt)
  304.                 self.option_strings[opt] = strings
  305.                 max_len = max(max_len, len(strings) + self.current_indent)
  306.             
  307.         
  308.         self.dedent()
  309.         self.dedent()
  310.         self.help_position = min(max_len + 2, self.max_help_position)
  311.         self.help_width = self.width - self.help_position
  312.  
  313.     
  314.     def format_option_strings(self, option):
  315.         '''Return a comma-separated list of option strings & metavariables.'''
  316.         return ', '.join(opts)
  317.  
  318.  
  319.  
  320. class IndentedHelpFormatter(HelpFormatter):
  321.     '''Format help with indented section bodies.
  322.     '''
  323.     
  324.     def __init__(self, indent_increment = 2, max_help_position = 24, width = None, short_first = 1):
  325.         HelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
  326.  
  327.     
  328.     def format_usage(self, usage):
  329.         return _('Usage: %s\n') % usage
  330.  
  331.     
  332.     def format_heading(self, heading):
  333.         return '%*s%s:\n' % (self.current_indent, '', heading)
  334.  
  335.  
  336.  
  337. class TitledHelpFormatter(HelpFormatter):
  338.     '''Format help with underlined section headers.
  339.     '''
  340.     
  341.     def __init__(self, indent_increment = 0, max_help_position = 24, width = None, short_first = 0):
  342.         HelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
  343.  
  344.     
  345.     def format_usage(self, usage):
  346.         return '%s  %s\n' % (self.format_heading(_('Usage')), usage)
  347.  
  348.     
  349.     def format_heading(self, heading):
  350.         return '%s\n%s\n' % (heading, '=-'[self.level] * len(heading))
  351.  
  352.  
  353.  
  354. def _parse_num(val, type):
  355.     if val[:2].lower() == '0x':
  356.         radix = 16
  357.     elif val[:2].lower() == '0b':
  358.         radix = 2
  359.         if not val[2:]:
  360.             pass
  361.         val = '0'
  362.     elif val[:1] == '0':
  363.         radix = 8
  364.     else:
  365.         radix = 10
  366.     return type(val, radix)
  367.  
  368.  
  369. def _parse_int(val):
  370.     return _parse_num(val, int)
  371.  
  372.  
  373. def _parse_long(val):
  374.     return _parse_num(val, long)
  375.  
  376. _builtin_cvt = {
  377.     'int': (_parse_int, _('integer')),
  378.     'long': (_parse_long, _('long integer')),
  379.     'float': (float, _('floating-point')),
  380.     'complex': (complex, _('complex')) }
  381.  
  382. def check_builtin(option, opt, value):
  383.     (cvt, what) = _builtin_cvt[option.type]
  384.     
  385.     try:
  386.         return cvt(value)
  387.     except ValueError:
  388.         raise OptionValueError(_('option %s: invalid %s value: %r') % (opt, what, value))
  389.  
  390.  
  391.  
  392. def check_choice(option, opt, value):
  393.     if value in option.choices:
  394.         return value
  395.     else:
  396.         choices = ', '.join(map(repr, option.choices))
  397.         raise OptionValueError(_('option %s: invalid choice: %r (choose from %s)') % (opt, value, choices))
  398.  
  399. NO_DEFAULT = ('NO', 'DEFAULT')
  400.  
  401. class Option:
  402.     '''
  403.     Instance attributes:
  404.       _short_opts : [string]
  405.       _long_opts : [string]
  406.  
  407.       action : string
  408.       type : string
  409.       dest : string
  410.       default : any
  411.       nargs : int
  412.       const : any
  413.       choices : [string]
  414.       callback : function
  415.       callback_args : (any*)
  416.       callback_kwargs : { string : any }
  417.       help : string
  418.       metavar : string
  419.     '''
  420.     ATTRS = [
  421.         'action',
  422.         'type',
  423.         'dest',
  424.         'default',
  425.         'nargs',
  426.         'const',
  427.         'choices',
  428.         'callback',
  429.         'callback_args',
  430.         'callback_kwargs',
  431.         'help',
  432.         'metavar']
  433.     ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'append_const', 'count', 'callback', 'help', 'version')
  434.     STORE_ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'append_const', 'count')
  435.     TYPED_ACTIONS = ('store', 'append', 'callback')
  436.     ALWAYS_TYPED_ACTIONS = ('store', 'append')
  437.     CONST_ACTIONS = ('store_const', 'append_const')
  438.     TYPES = ('string', 'int', 'long', 'float', 'complex', 'choice')
  439.     TYPE_CHECKER = {
  440.         'int': check_builtin,
  441.         'long': check_builtin,
  442.         'float': check_builtin,
  443.         'complex': check_builtin,
  444.         'choice': check_choice }
  445.     CHECK_METHODS = None
  446.     
  447.     def __init__(self, *opts, **attrs):
  448.         self._short_opts = []
  449.         self._long_opts = []
  450.         opts = self._check_opt_strings(opts)
  451.         self._set_opt_strings(opts)
  452.         self._set_attrs(attrs)
  453.         for checker in self.CHECK_METHODS:
  454.             checker(self)
  455.         
  456.  
  457.     
  458.     def _check_opt_strings(self, opts):
  459.         opts = filter(None, opts)
  460.         if not opts:
  461.             raise TypeError('at least one option string must be supplied')
  462.         
  463.         return opts
  464.  
  465.     
  466.     def _set_opt_strings(self, opts):
  467.         for opt in opts:
  468.             if len(opt) < 2:
  469.                 raise OptionError('invalid option string %r: must be at least two characters long' % opt, self)
  470.                 continue
  471.             if len(opt) == 2:
  472.                 if not opt[0] == '-' and opt[1] != '-':
  473.                     raise OptionError('invalid short option string %r: must be of the form -x, (x any non-dash char)' % opt, self)
  474.                 
  475.                 self._short_opts.append(opt)
  476.                 continue
  477.             if not opt[0:2] == '--' and opt[2] != '-':
  478.                 raise OptionError('invalid long option string %r: must start with --, followed by non-dash' % opt, self)
  479.             
  480.             self._long_opts.append(opt)
  481.         
  482.  
  483.     
  484.     def _set_attrs(self, attrs):
  485.         for attr in self.ATTRS:
  486.             if attrs.has_key(attr):
  487.                 setattr(self, attr, attrs[attr])
  488.                 del attrs[attr]
  489.                 continue
  490.             if attr == 'default':
  491.                 setattr(self, attr, NO_DEFAULT)
  492.                 continue
  493.             setattr(self, attr, None)
  494.         
  495.         if attrs:
  496.             attrs = attrs.keys()
  497.             attrs.sort()
  498.             raise OptionError('invalid keyword arguments: %s' % ', '.join(attrs), self)
  499.         
  500.  
  501.     
  502.     def _check_action(self):
  503.         if self.action is None:
  504.             self.action = 'store'
  505.         elif self.action not in self.ACTIONS:
  506.             raise OptionError('invalid action: %r' % self.action, self)
  507.         
  508.  
  509.     
  510.     def _check_type(self):
  511.         if self.type is None:
  512.             if self.action in self.ALWAYS_TYPED_ACTIONS:
  513.                 if self.choices is not None:
  514.                     self.type = 'choice'
  515.                 else:
  516.                     self.type = 'string'
  517.             
  518.         else:
  519.             import __builtin__
  520.             if (type(self.type) is types.TypeType or hasattr(self.type, '__name__')) and getattr(__builtin__, self.type.__name__, None) is self.type:
  521.                 self.type = self.type.__name__
  522.             
  523.             if self.type == 'str':
  524.                 self.type = 'string'
  525.             
  526.             if self.type not in self.TYPES:
  527.                 raise OptionError('invalid option type: %r' % self.type, self)
  528.             
  529.             if self.action not in self.TYPED_ACTIONS:
  530.                 raise OptionError('must not supply a type for action %r' % self.action, self)
  531.             
  532.  
  533.     
  534.     def _check_choice(self):
  535.         if self.type == 'choice':
  536.             if self.choices is None:
  537.                 raise OptionError("must supply a list of choices for type 'choice'", self)
  538.             elif type(self.choices) not in (types.TupleType, types.ListType):
  539.                 raise OptionError("choices must be a list of strings ('%s' supplied)" % str(type(self.choices)).split("'")[1], self)
  540.             
  541.         elif self.choices is not None:
  542.             raise OptionError('must not supply choices for type %r' % self.type, self)
  543.         
  544.  
  545.     
  546.     def _check_dest(self):
  547.         if not self.action in self.STORE_ACTIONS:
  548.             pass
  549.         takes_value = self.type is not None
  550.         if self.dest is None and takes_value:
  551.             if self._long_opts:
  552.                 self.dest = self._long_opts[0][2:].replace('-', '_')
  553.             else:
  554.                 self.dest = self._short_opts[0][1]
  555.         
  556.  
  557.     
  558.     def _check_const(self):
  559.         if self.action not in self.CONST_ACTIONS and self.const is not None:
  560.             raise OptionError("'const' must not be supplied for action %r" % self.action, self)
  561.         
  562.  
  563.     
  564.     def _check_nargs(self):
  565.         if self.action in self.TYPED_ACTIONS:
  566.             if self.nargs is None:
  567.                 self.nargs = 1
  568.             
  569.         elif self.nargs is not None:
  570.             raise OptionError("'nargs' must not be supplied for action %r" % self.action, self)
  571.         
  572.  
  573.     
  574.     def _check_callback(self):
  575.         if self.action == 'callback':
  576.             if not callable(self.callback):
  577.                 raise OptionError('callback not callable: %r' % self.callback, self)
  578.             
  579.             if self.callback_args is not None and type(self.callback_args) is not types.TupleType:
  580.                 raise OptionError('callback_args, if supplied, must be a tuple: not %r' % self.callback_args, self)
  581.             
  582.             if self.callback_kwargs is not None and type(self.callback_kwargs) is not types.DictType:
  583.                 raise OptionError('callback_kwargs, if supplied, must be a dict: not %r' % self.callback_kwargs, self)
  584.             
  585.         elif self.callback is not None:
  586.             raise OptionError('callback supplied (%r) for non-callback option' % self.callback, self)
  587.         
  588.         if self.callback_args is not None:
  589.             raise OptionError('callback_args supplied for non-callback option', self)
  590.         
  591.         if self.callback_kwargs is not None:
  592.             raise OptionError('callback_kwargs supplied for non-callback option', self)
  593.         
  594.  
  595.     CHECK_METHODS = [
  596.         _check_action,
  597.         _check_type,
  598.         _check_choice,
  599.         _check_dest,
  600.         _check_const,
  601.         _check_nargs,
  602.         _check_callback]
  603.     
  604.     def __str__(self):
  605.         return '/'.join(self._short_opts + self._long_opts)
  606.  
  607.     __repr__ = _repr
  608.     
  609.     def takes_value(self):
  610.         return self.type is not None
  611.  
  612.     
  613.     def get_opt_string(self):
  614.         if self._long_opts:
  615.             return self._long_opts[0]
  616.         else:
  617.             return self._short_opts[0]
  618.  
  619.     
  620.     def check_value(self, opt, value):
  621.         checker = self.TYPE_CHECKER.get(self.type)
  622.         if checker is None:
  623.             return value
  624.         else:
  625.             return checker(self, opt, value)
  626.  
  627.     
  628.     def convert_value(self, opt, value):
  629.         pass
  630.  
  631.     
  632.     def process(self, opt, value, values, parser):
  633.         value = self.convert_value(opt, value)
  634.         return self.take_action(self.action, self.dest, opt, value, values, parser)
  635.  
  636.     
  637.     def take_action(self, action, dest, opt, value, values, parser):
  638.         if action == 'store':
  639.             setattr(values, dest, value)
  640.         elif action == 'store_const':
  641.             setattr(values, dest, self.const)
  642.         elif action == 'store_true':
  643.             setattr(values, dest, True)
  644.         elif action == 'store_false':
  645.             setattr(values, dest, False)
  646.         elif action == 'append':
  647.             values.ensure_value(dest, []).append(value)
  648.         elif action == 'append_const':
  649.             values.ensure_value(dest, []).append(self.const)
  650.         elif action == 'count':
  651.             setattr(values, dest, values.ensure_value(dest, 0) + 1)
  652.         elif action == 'callback':
  653.             if not self.callback_args:
  654.                 pass
  655.             args = ()
  656.             if not self.callback_kwargs:
  657.                 pass
  658.             kwargs = { }
  659.             self.callback(self, opt, value, parser, *args, **kwargs)
  660.         elif action == 'help':
  661.             parser.print_help()
  662.             parser.exit()
  663.         elif action == 'version':
  664.             parser.print_version()
  665.             parser.exit()
  666.         else:
  667.             raise RuntimeError, 'unknown action %r' % self.action
  668.         return 1
  669.  
  670.  
  671. SUPPRESS_HELP = 'SUPPRESS' + 'HELP'
  672. SUPPRESS_USAGE = 'SUPPRESS' + 'USAGE'
  673.  
  674. try:
  675.     (True, False)
  676. except NameError:
  677.     (True, False) = (1, 0)
  678.  
  679.  
  680. def isbasestring(x):
  681.     if not isinstance(x, types.StringType):
  682.         pass
  683.     return isinstance(x, types.UnicodeType)
  684.  
  685.  
  686. class Values:
  687.     
  688.     def __init__(self, defaults = None):
  689.         if defaults:
  690.             for attr, val in defaults.items():
  691.                 setattr(self, attr, val)
  692.             
  693.         
  694.  
  695.     
  696.     def __str__(self):
  697.         return str(self.__dict__)
  698.  
  699.     __repr__ = _repr
  700.     
  701.     def __cmp__(self, other):
  702.         if isinstance(other, Values):
  703.             return cmp(self.__dict__, other.__dict__)
  704.         elif isinstance(other, types.DictType):
  705.             return cmp(self.__dict__, other)
  706.         else:
  707.             return -1
  708.  
  709.     
  710.     def _update_careful(self, dict):
  711.         '''
  712.         Update the option values from an arbitrary dictionary, but only
  713.         use keys from dict that already have a corresponding attribute
  714.         in self.  Any keys in dict without a corresponding attribute
  715.         are silently ignored.
  716.         '''
  717.         for attr in dir(self):
  718.             if dict.has_key(attr):
  719.                 dval = dict[attr]
  720.                 if dval is not None:
  721.                     setattr(self, attr, dval)
  722.                 
  723.             dval is not None
  724.         
  725.  
  726.     
  727.     def _update_loose(self, dict):
  728.         '''
  729.         Update the option values from an arbitrary dictionary,
  730.         using all keys from the dictionary regardless of whether
  731.         they have a corresponding attribute in self or not.
  732.         '''
  733.         self.__dict__.update(dict)
  734.  
  735.     
  736.     def _update(self, dict, mode):
  737.         if mode == 'careful':
  738.             self._update_careful(dict)
  739.         elif mode == 'loose':
  740.             self._update_loose(dict)
  741.         else:
  742.             raise ValueError, 'invalid update mode: %r' % mode
  743.  
  744.     
  745.     def read_module(self, modname, mode = 'careful'):
  746.         __import__(modname)
  747.         mod = sys.modules[modname]
  748.         self._update(vars(mod), mode)
  749.  
  750.     
  751.     def read_file(self, filename, mode = 'careful'):
  752.         vars = { }
  753.         execfile(filename, vars)
  754.         self._update(vars, mode)
  755.  
  756.     
  757.     def ensure_value(self, attr, value):
  758.         if not hasattr(self, attr) or getattr(self, attr) is None:
  759.             setattr(self, attr, value)
  760.         
  761.         return getattr(self, attr)
  762.  
  763.  
  764.  
  765. class OptionContainer:
  766.     '''
  767.     Abstract base class.
  768.  
  769.     Class attributes:
  770.       standard_option_list : [Option]
  771.         list of standard options that will be accepted by all instances
  772.         of this parser class (intended to be overridden by subclasses).
  773.  
  774.     Instance attributes:
  775.       option_list : [Option]
  776.         the list of Option objects contained by this OptionContainer
  777.       _short_opt : { string : Option }
  778.         dictionary mapping short option strings, eg. "-f" or "-X",
  779.         to the Option instances that implement them.  If an Option
  780.         has multiple short option strings, it will appears in this
  781.         dictionary multiple times. [1]
  782.       _long_opt : { string : Option }
  783.         dictionary mapping long option strings, eg. "--file" or
  784.         "--exclude", to the Option instances that implement them.
  785.         Again, a given Option can occur multiple times in this
  786.         dictionary. [1]
  787.       defaults : { string : any }
  788.         dictionary mapping option destination names to default
  789.         values for each destination [1]
  790.  
  791.     [1] These mappings are common to (shared by) all components of the
  792.         controlling OptionParser, where they are initially created.
  793.  
  794.     '''
  795.     
  796.     def __init__(self, option_class, conflict_handler, description):
  797.         self._create_option_list()
  798.         self.option_class = option_class
  799.         self.set_conflict_handler(conflict_handler)
  800.         self.set_description(description)
  801.  
  802.     
  803.     def _create_option_mappings(self):
  804.         self._short_opt = { }
  805.         self._long_opt = { }
  806.         self.defaults = { }
  807.  
  808.     
  809.     def _share_option_mappings(self, parser):
  810.         self._short_opt = parser._short_opt
  811.         self._long_opt = parser._long_opt
  812.         self.defaults = parser.defaults
  813.  
  814.     
  815.     def set_conflict_handler(self, handler):
  816.         if handler not in ('error', 'resolve'):
  817.             raise ValueError, 'invalid conflict_resolution value %r' % handler
  818.         
  819.         self.conflict_handler = handler
  820.  
  821.     
  822.     def set_description(self, description):
  823.         self.description = description
  824.  
  825.     
  826.     def get_description(self):
  827.         return self.description
  828.  
  829.     
  830.     def destroy(self):
  831.         '''see OptionParser.destroy().'''
  832.         del self._short_opt
  833.         del self._long_opt
  834.         del self.defaults
  835.  
  836.     
  837.     def _check_conflict(self, option):
  838.         conflict_opts = []
  839.         for opt in option._short_opts:
  840.             if self._short_opt.has_key(opt):
  841.                 conflict_opts.append((opt, self._short_opt[opt]))
  842.                 continue
  843.         
  844.         for opt in option._long_opts:
  845.             if self._long_opt.has_key(opt):
  846.                 conflict_opts.append((opt, self._long_opt[opt]))
  847.                 continue
  848.         
  849.         if conflict_opts:
  850.             handler = self.conflict_handler
  851.             if handler == 'error':
  852.                 raise ', '.join([] % []([ co[0] for co in conflict_opts ]), option)
  853.             elif handler == 'resolve':
  854.                 for opt, c_option in conflict_opts:
  855.                     if opt.startswith('--'):
  856.                         c_option._long_opts.remove(opt)
  857.                         del self._long_opt[opt]
  858.                     else:
  859.                         c_option._short_opts.remove(opt)
  860.                         del self._short_opt[opt]
  861.                     if not c_option._short_opts or c_option._long_opts:
  862.                         c_option.container.option_list.remove(c_option)
  863.                         continue
  864.                 
  865.             
  866.         
  867.  
  868.     
  869.     def add_option(self, *args, **kwargs):
  870.         '''add_option(Option)
  871.            add_option(opt_str, ..., kwarg=val, ...)
  872.         '''
  873.         if type(args[0]) is types.StringType:
  874.             option = self.option_class(*args, **kwargs)
  875.         elif len(args) == 1 and not kwargs:
  876.             option = args[0]
  877.             if not isinstance(option, Option):
  878.                 raise TypeError, 'not an Option instance: %r' % option
  879.             
  880.         else:
  881.             raise TypeError, 'invalid arguments'
  882.         self._check_conflict(option)
  883.         self.option_list.append(option)
  884.         option.container = self
  885.         for opt in option._short_opts:
  886.             self._short_opt[opt] = option
  887.         
  888.         for opt in option._long_opts:
  889.             self._long_opt[opt] = option
  890.         
  891.         if option.dest is not None:
  892.             if option.default is not NO_DEFAULT:
  893.                 self.defaults[option.dest] = option.default
  894.             elif not self.defaults.has_key(option.dest):
  895.                 self.defaults[option.dest] = None
  896.             
  897.         
  898.         return option
  899.  
  900.     
  901.     def add_options(self, option_list):
  902.         for option in option_list:
  903.             self.add_option(option)
  904.         
  905.  
  906.     
  907.     def get_option(self, opt_str):
  908.         if not self._short_opt.get(opt_str):
  909.             pass
  910.         return self._long_opt.get(opt_str)
  911.  
  912.     
  913.     def has_option(self, opt_str):
  914.         if not self._short_opt.has_key(opt_str):
  915.             pass
  916.         return self._long_opt.has_key(opt_str)
  917.  
  918.     
  919.     def remove_option(self, opt_str):
  920.         option = self._short_opt.get(opt_str)
  921.         if option is None:
  922.             option = self._long_opt.get(opt_str)
  923.         
  924.         if option is None:
  925.             raise ValueError('no such option %r' % opt_str)
  926.         
  927.         for opt in option._short_opts:
  928.             del self._short_opt[opt]
  929.         
  930.         for opt in option._long_opts:
  931.             del self._long_opt[opt]
  932.         
  933.         option.container.option_list.remove(option)
  934.  
  935.     
  936.     def format_option_help(self, formatter):
  937.         if not self.option_list:
  938.             return ''
  939.         
  940.         result = []
  941.         for option in self.option_list:
  942.             if option.help is not SUPPRESS_HELP:
  943.                 result.append(formatter.format_option(option))
  944.                 continue
  945.         
  946.         return ''.join(result)
  947.  
  948.     
  949.     def format_description(self, formatter):
  950.         return formatter.format_description(self.get_description())
  951.  
  952.     
  953.     def format_help(self, formatter):
  954.         result = []
  955.         if self.description:
  956.             result.append(self.format_description(formatter))
  957.         
  958.         if self.option_list:
  959.             result.append(self.format_option_help(formatter))
  960.         
  961.         return '\n'.join(result)
  962.  
  963.  
  964.  
  965. class OptionGroup(OptionContainer):
  966.     
  967.     def __init__(self, parser, title, description = None):
  968.         self.parser = parser
  969.         OptionContainer.__init__(self, parser.option_class, parser.conflict_handler, description)
  970.         self.title = title
  971.  
  972.     
  973.     def _create_option_list(self):
  974.         self.option_list = []
  975.         self._share_option_mappings(self.parser)
  976.  
  977.     
  978.     def set_title(self, title):
  979.         self.title = title
  980.  
  981.     
  982.     def destroy(self):
  983.         '''see OptionParser.destroy().'''
  984.         OptionContainer.destroy(self)
  985.         del self.option_list
  986.  
  987.     
  988.     def format_help(self, formatter):
  989.         result = formatter.format_heading(self.title)
  990.         formatter.indent()
  991.         result += OptionContainer.format_help(self, formatter)
  992.         formatter.dedent()
  993.         return result
  994.  
  995.  
  996.  
  997. class OptionParser(OptionContainer):
  998.     '''
  999.     Class attributes:
  1000.       standard_option_list : [Option]
  1001.         list of standard options that will be accepted by all instances
  1002.         of this parser class (intended to be overridden by subclasses).
  1003.  
  1004.     Instance attributes:
  1005.       usage : string
  1006.         a usage string for your program.  Before it is displayed
  1007.         to the user, "%prog" will be expanded to the name of
  1008.         your program (self.prog or os.path.basename(sys.argv[0])).
  1009.       prog : string
  1010.         the name of the current program (to override
  1011.         os.path.basename(sys.argv[0])).
  1012.       epilog : string
  1013.         paragraph of help text to print after option help
  1014.  
  1015.       option_groups : [OptionGroup]
  1016.         list of option groups in this parser (option groups are
  1017.         irrelevant for parsing the command-line, but very useful
  1018.         for generating help)
  1019.  
  1020.       allow_interspersed_args : bool = true
  1021.         if true, positional arguments may be interspersed with options.
  1022.         Assuming -a and -b each take a single argument, the command-line
  1023.           -ablah foo bar -bboo baz
  1024.         will be interpreted the same as
  1025.           -ablah -bboo -- foo bar baz
  1026.         If this flag were false, that command line would be interpreted as
  1027.           -ablah -- foo bar -bboo baz
  1028.         -- ie. we stop processing options as soon as we see the first
  1029.         non-option argument.  (This is the tradition followed by
  1030.         Python\'s getopt module, Perl\'s Getopt::Std, and other argument-
  1031.         parsing libraries, but it is generally annoying to users.)
  1032.  
  1033.       process_default_values : bool = true
  1034.         if true, option default values are processed similarly to option
  1035.         values from the command line: that is, they are passed to the
  1036.         type-checking function for the option\'s type (as long as the
  1037.         default value is a string).  (This really only matters if you
  1038.         have defined custom types; see SF bug #955889.)  Set it to false
  1039.         to restore the behaviour of Optik 1.4.1 and earlier.
  1040.  
  1041.       rargs : [string]
  1042.         the argument list currently being parsed.  Only set when
  1043.         parse_args() is active, and continually trimmed down as
  1044.         we consume arguments.  Mainly there for the benefit of
  1045.         callback options.
  1046.       largs : [string]
  1047.         the list of leftover arguments that we have skipped while
  1048.         parsing options.  If allow_interspersed_args is false, this
  1049.         list is always empty.
  1050.       values : Values
  1051.         the set of option values currently being accumulated.  Only
  1052.         set when parse_args() is active.  Also mainly for callbacks.
  1053.  
  1054.     Because of the \'rargs\', \'largs\', and \'values\' attributes,
  1055.     OptionParser is not thread-safe.  If, for some perverse reason, you
  1056.     need to parse command-line arguments simultaneously in different
  1057.     threads, use different OptionParser instances.
  1058.  
  1059.     '''
  1060.     standard_option_list = []
  1061.     
  1062.     def __init__(self, usage = None, option_list = None, option_class = Option, version = None, conflict_handler = 'error', description = None, formatter = None, add_help_option = True, prog = None, epilog = None):
  1063.         OptionContainer.__init__(self, option_class, conflict_handler, description)
  1064.         self.set_usage(usage)
  1065.         self.prog = prog
  1066.         self.version = version
  1067.         self.allow_interspersed_args = True
  1068.         self.process_default_values = True
  1069.         if formatter is None:
  1070.             formatter = IndentedHelpFormatter()
  1071.         
  1072.         self.formatter = formatter
  1073.         self.formatter.set_parser(self)
  1074.         self.epilog = epilog
  1075.         self._populate_option_list(option_list, add_help = add_help_option)
  1076.         self._init_parsing_state()
  1077.  
  1078.     
  1079.     def destroy(self):
  1080.         '''
  1081.         Declare that you are done with this OptionParser.  This cleans up
  1082.         reference cycles so the OptionParser (and all objects referenced by
  1083.         it) can be garbage-collected promptly.  After calling destroy(), the
  1084.         OptionParser is unusable.
  1085.         '''
  1086.         OptionContainer.destroy(self)
  1087.         for group in self.option_groups:
  1088.             group.destroy()
  1089.         
  1090.         del self.option_list
  1091.         del self.option_groups
  1092.         del self.formatter
  1093.  
  1094.     
  1095.     def _create_option_list(self):
  1096.         self.option_list = []
  1097.         self.option_groups = []
  1098.         self._create_option_mappings()
  1099.  
  1100.     
  1101.     def _add_help_option(self):
  1102.         self.add_option('-h', '--help', action = 'help', help = _('show this help message and exit'))
  1103.  
  1104.     
  1105.     def _add_version_option(self):
  1106.         self.add_option('--version', action = 'version', help = _("show program's version number and exit"))
  1107.  
  1108.     
  1109.     def _populate_option_list(self, option_list, add_help = True):
  1110.         if self.standard_option_list:
  1111.             self.add_options(self.standard_option_list)
  1112.         
  1113.         if option_list:
  1114.             self.add_options(option_list)
  1115.         
  1116.         if self.version:
  1117.             self._add_version_option()
  1118.         
  1119.         if add_help:
  1120.             self._add_help_option()
  1121.         
  1122.  
  1123.     
  1124.     def _init_parsing_state(self):
  1125.         self.rargs = None
  1126.         self.largs = None
  1127.         self.values = None
  1128.  
  1129.     
  1130.     def set_usage(self, usage):
  1131.         if usage is None:
  1132.             self.usage = _('%prog [options]')
  1133.         elif usage is SUPPRESS_USAGE:
  1134.             self.usage = None
  1135.         elif usage.lower().startswith('usage: '):
  1136.             self.usage = usage[7:]
  1137.         else:
  1138.             self.usage = usage
  1139.  
  1140.     
  1141.     def enable_interspersed_args(self):
  1142.         self.allow_interspersed_args = True
  1143.  
  1144.     
  1145.     def disable_interspersed_args(self):
  1146.         self.allow_interspersed_args = False
  1147.  
  1148.     
  1149.     def set_process_default_values(self, process):
  1150.         self.process_default_values = process
  1151.  
  1152.     
  1153.     def set_default(self, dest, value):
  1154.         self.defaults[dest] = value
  1155.  
  1156.     
  1157.     def set_defaults(self, **kwargs):
  1158.         self.defaults.update(kwargs)
  1159.  
  1160.     
  1161.     def _get_all_options(self):
  1162.         options = self.option_list[:]
  1163.         for group in self.option_groups:
  1164.             options.extend(group.option_list)
  1165.         
  1166.         return options
  1167.  
  1168.     
  1169.     def get_default_values(self):
  1170.         if not self.process_default_values:
  1171.             return Values(self.defaults)
  1172.         
  1173.         defaults = self.defaults.copy()
  1174.         for option in self._get_all_options():
  1175.             default = defaults.get(option.dest)
  1176.             if isbasestring(default):
  1177.                 opt_str = option.get_opt_string()
  1178.                 defaults[option.dest] = option.check_value(opt_str, default)
  1179.                 continue
  1180.         
  1181.         return Values(defaults)
  1182.  
  1183.     
  1184.     def add_option_group(self, *args, **kwargs):
  1185.         if type(args[0]) is types.StringType:
  1186.             group = OptionGroup(self, *args, **kwargs)
  1187.         elif len(args) == 1 and not kwargs:
  1188.             group = args[0]
  1189.             if not isinstance(group, OptionGroup):
  1190.                 raise TypeError, 'not an OptionGroup instance: %r' % group
  1191.             
  1192.             if group.parser is not self:
  1193.                 raise ValueError, 'invalid OptionGroup (wrong parser)'
  1194.             
  1195.         else:
  1196.             raise TypeError, 'invalid arguments'
  1197.         self.option_groups.append(group)
  1198.         return group
  1199.  
  1200.     
  1201.     def get_option_group(self, opt_str):
  1202.         if not self._short_opt.get(opt_str):
  1203.             pass
  1204.         option = self._long_opt.get(opt_str)
  1205.         if option and option.container is not self:
  1206.             return option.container
  1207.         
  1208.  
  1209.     
  1210.     def _get_args(self, args):
  1211.         if args is None:
  1212.             return sys.argv[1:]
  1213.         else:
  1214.             return args[:]
  1215.  
  1216.     
  1217.     def parse_args(self, args = None, values = None):
  1218.         """
  1219.         parse_args(args : [string] = sys.argv[1:],
  1220.                    values : Values = None)
  1221.         -> (values : Values, args : [string])
  1222.  
  1223.         Parse the command-line options found in 'args' (default:
  1224.         sys.argv[1:]).  Any errors result in a call to 'error()', which
  1225.         by default prints the usage message to stderr and calls
  1226.         sys.exit() with an error message.  On success returns a pair
  1227.         (values, args) where 'values' is an Values instance (with all
  1228.         your option values) and 'args' is the list of arguments left
  1229.         over after parsing options.
  1230.         """
  1231.         rargs = self._get_args(args)
  1232.         if values is None:
  1233.             values = self.get_default_values()
  1234.         
  1235.         self.rargs = rargs
  1236.         self.largs = largs = []
  1237.         self.values = values
  1238.         
  1239.         try:
  1240.             stop = self._process_args(largs, rargs, values)
  1241.         except (BadOptionError, OptionValueError):
  1242.             err = None
  1243.             self.error(str(err))
  1244.  
  1245.         args = largs + rargs
  1246.         return self.check_values(values, args)
  1247.  
  1248.     
  1249.     def check_values(self, values, args):
  1250.         '''
  1251.         check_values(values : Values, args : [string])
  1252.         -> (values : Values, args : [string])
  1253.  
  1254.         Check that the supplied option values and leftover arguments are
  1255.         valid.  Returns the option values and leftover arguments
  1256.         (possibly adjusted, possibly completely new -- whatever you
  1257.         like).  Default implementation just returns the passed-in
  1258.         values; subclasses may override as desired.
  1259.         '''
  1260.         return (values, args)
  1261.  
  1262.     
  1263.     def _process_args(self, largs, rargs, values):
  1264.         """_process_args(largs : [string],
  1265.                          rargs : [string],
  1266.                          values : Values)
  1267.  
  1268.         Process command-line arguments and populate 'values', consuming
  1269.         options and arguments from 'rargs'.  If 'allow_interspersed_args' is
  1270.         false, stop at the first non-option argument.  If true, accumulate any
  1271.         interspersed non-option arguments in 'largs'.
  1272.         """
  1273.         while rargs:
  1274.             arg = rargs[0]
  1275.             if arg == '--':
  1276.                 del rargs[0]
  1277.                 return None
  1278.                 continue
  1279.             if arg[0:2] == '--':
  1280.                 self._process_long_opt(rargs, values)
  1281.                 continue
  1282.             if arg[:1] == '-' and len(arg) > 1:
  1283.                 self._process_short_opts(rargs, values)
  1284.                 continue
  1285.             if self.allow_interspersed_args:
  1286.                 largs.append(arg)
  1287.                 del rargs[0]
  1288.                 continue
  1289.             return None
  1290.  
  1291.     
  1292.     def _match_long_opt(self, opt):
  1293.         """_match_long_opt(opt : string) -> string
  1294.  
  1295.         Determine which long option string 'opt' matches, ie. which one
  1296.         it is an unambiguous abbrevation for.  Raises BadOptionError if
  1297.         'opt' doesn't unambiguously match any long option string.
  1298.         """
  1299.         return _match_abbrev(opt, self._long_opt)
  1300.  
  1301.     
  1302.     def _process_long_opt(self, rargs, values):
  1303.         arg = rargs.pop(0)
  1304.         if '=' in arg:
  1305.             (opt, next_arg) = arg.split('=', 1)
  1306.             rargs.insert(0, next_arg)
  1307.             had_explicit_value = True
  1308.         else:
  1309.             opt = arg
  1310.             had_explicit_value = False
  1311.         opt = self._match_long_opt(opt)
  1312.         option = self._long_opt[opt]
  1313.         if option.takes_value():
  1314.             nargs = option.nargs
  1315.             if len(rargs) < nargs:
  1316.                 if nargs == 1:
  1317.                     self.error(_('%s option requires an argument') % opt)
  1318.                 else:
  1319.                     self.error(_('%s option requires %d arguments') % (opt, nargs))
  1320.             elif nargs == 1:
  1321.                 value = rargs.pop(0)
  1322.             else:
  1323.                 value = tuple(rargs[0:nargs])
  1324.                 del rargs[0:nargs]
  1325.         elif had_explicit_value:
  1326.             self.error(_('%s option does not take a value') % opt)
  1327.         else:
  1328.             value = None
  1329.         option.process(opt, value, values, self)
  1330.  
  1331.     
  1332.     def _process_short_opts(self, rargs, values):
  1333.         arg = rargs.pop(0)
  1334.         stop = False
  1335.         i = 1
  1336.         for ch in arg[1:]:
  1337.             opt = '-' + ch
  1338.             option = self._short_opt.get(opt)
  1339.             i += 1
  1340.             if not option:
  1341.                 raise BadOptionError(opt)
  1342.             
  1343.             if option.takes_value():
  1344.                 if i < len(arg):
  1345.                     rargs.insert(0, arg[i:])
  1346.                     stop = True
  1347.                 
  1348.                 nargs = option.nargs
  1349.                 if len(rargs) < nargs:
  1350.                     if nargs == 1:
  1351.                         self.error(_('%s option requires an argument') % opt)
  1352.                     else:
  1353.                         self.error(_('%s option requires %d arguments') % (opt, nargs))
  1354.                 elif nargs == 1:
  1355.                     value = rargs.pop(0)
  1356.                 else:
  1357.                     value = tuple(rargs[0:nargs])
  1358.                     del rargs[0:nargs]
  1359.             else:
  1360.                 value = None
  1361.             option.process(opt, value, values, self)
  1362.             if stop:
  1363.                 break
  1364.                 continue
  1365.         
  1366.  
  1367.     
  1368.     def get_prog_name(self):
  1369.         if self.prog is None:
  1370.             return os.path.basename(sys.argv[0])
  1371.         else:
  1372.             return self.prog
  1373.  
  1374.     
  1375.     def expand_prog_name(self, s):
  1376.         return s.replace('%prog', self.get_prog_name())
  1377.  
  1378.     
  1379.     def get_description(self):
  1380.         return self.expand_prog_name(self.description)
  1381.  
  1382.     
  1383.     def exit(self, status = 0, msg = None):
  1384.         if msg:
  1385.             sys.stderr.write(msg)
  1386.         
  1387.         sys.exit(status)
  1388.  
  1389.     
  1390.     def error(self, msg):
  1391.         """error(msg : string)
  1392.  
  1393.         Print a usage message incorporating 'msg' to stderr and exit.
  1394.         If you override this in a subclass, it should not return -- it
  1395.         should either exit or raise an exception.
  1396.         """
  1397.         self.print_usage(sys.stderr)
  1398.         self.exit(2, '%s: error: %s\n' % (self.get_prog_name(), msg))
  1399.  
  1400.     
  1401.     def get_usage(self):
  1402.         if self.usage:
  1403.             return self.formatter.format_usage(self.expand_prog_name(self.usage))
  1404.         else:
  1405.             return ''
  1406.  
  1407.     
  1408.     def print_usage(self, file = None):
  1409.         '''print_usage(file : file = stdout)
  1410.  
  1411.         Print the usage message for the current program (self.usage) to
  1412.         \'file\' (default stdout).  Any occurence of the string "%prog" in
  1413.         self.usage is replaced with the name of the current program
  1414.         (basename of sys.argv[0]).  Does nothing if self.usage is empty
  1415.         or not defined.
  1416.         '''
  1417.         if self.usage:
  1418.             print >>file, self.get_usage()
  1419.         
  1420.  
  1421.     
  1422.     def get_version(self):
  1423.         if self.version:
  1424.             return self.expand_prog_name(self.version)
  1425.         else:
  1426.             return ''
  1427.  
  1428.     
  1429.     def print_version(self, file = None):
  1430.         '''print_version(file : file = stdout)
  1431.  
  1432.         Print the version message for this program (self.version) to
  1433.         \'file\' (default stdout).  As with print_usage(), any occurence
  1434.         of "%prog" in self.version is replaced by the current program\'s
  1435.         name.  Does nothing if self.version is empty or undefined.
  1436.         '''
  1437.         if self.version:
  1438.             print >>file, self.get_version()
  1439.         
  1440.  
  1441.     
  1442.     def format_option_help(self, formatter = None):
  1443.         if formatter is None:
  1444.             formatter = self.formatter
  1445.         
  1446.         formatter.store_option_strings(self)
  1447.         result = []
  1448.         result.append(formatter.format_heading(_('Options')))
  1449.         formatter.indent()
  1450.         if self.option_list:
  1451.             result.append(OptionContainer.format_option_help(self, formatter))
  1452.             result.append('\n')
  1453.         
  1454.         for group in self.option_groups:
  1455.             result.append(group.format_help(formatter))
  1456.             result.append('\n')
  1457.         
  1458.         formatter.dedent()
  1459.         return ''.join(result[:-1])
  1460.  
  1461.     
  1462.     def format_epilog(self, formatter):
  1463.         return formatter.format_epilog(self.epilog)
  1464.  
  1465.     
  1466.     def format_help(self, formatter = None):
  1467.         if formatter is None:
  1468.             formatter = self.formatter
  1469.         
  1470.         result = []
  1471.         if self.usage:
  1472.             result.append(self.get_usage() + '\n')
  1473.         
  1474.         if self.description:
  1475.             result.append(self.format_description(formatter) + '\n')
  1476.         
  1477.         result.append(self.format_option_help(formatter))
  1478.         result.append(self.format_epilog(formatter))
  1479.         return ''.join(result)
  1480.  
  1481.     
  1482.     def _get_encoding(self, file):
  1483.         encoding = getattr(file, 'encoding', None)
  1484.         if not encoding:
  1485.             encoding = sys.getdefaultencoding()
  1486.         
  1487.         return encoding
  1488.  
  1489.     
  1490.     def print_help(self, file = None):
  1491.         """print_help(file : file = stdout)
  1492.  
  1493.         Print an extended help message, listing all options and any
  1494.         help text provided with them, to 'file' (default stdout).
  1495.         """
  1496.         if file is None:
  1497.             file = sys.stdout
  1498.         
  1499.         encoding = self._get_encoding(file)
  1500.         file.write(self.format_help().encode(encoding, 'replace'))
  1501.  
  1502.  
  1503.  
  1504. def _match_abbrev(s, wordmap):
  1505.     """_match_abbrev(s : string, wordmap : {string : Option}) -> string
  1506.  
  1507.     Return the string key in 'wordmap' for which 's' is an unambiguous
  1508.     abbreviation.  If 's' is found to be ambiguous or doesn't match any of
  1509.     'words', raise BadOptionError.
  1510.     """
  1511.     if wordmap.has_key(s):
  1512.         return s
  1513.     else:
  1514.         possibilities = _[1]
  1515.         if len(possibilities) == 1:
  1516.             return possibilities[0]
  1517.         elif not possibilities:
  1518.             raise BadOptionError(s)
  1519.         else:
  1520.             possibilities.sort()
  1521.             raise AmbiguousOptionError(s, possibilities)
  1522.  
  1523. make_option = Option
  1524.